// pages/all/pages/heart/heart.js
const app = getApp()
var r = require('../../../../utils/request.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title:'',
    message:'',

    tempFilePaths: [], //图片路径
    wordSrc:{name:'',path:'',size:''},//word文档
    active:''
  },

  // 选择类型
  select() {
    var that = this
    wx.showActionSheet({
      itemList: ['图片', '文档'],
      success: function (res) {
        // console.log(res.tapIndex)
        
        if(res.tapIndex == 0){
          let wordSrc = {name:'',path:'',size:''}
          that.setData({
            active:res.tapIndex,
            wordSrc:wordSrc
          })
          that.chooseImage()
        }else if(res.tapIndex==1){
          that.setData({
            active:res.tapIndex,
            tempFilePaths:[]
          })
          that.chooseWord()
        }
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },

  chooseImage(e) { //选择图片
    let that = this;
    wx.chooseImage({
      count: 1, // 可上传图片数量
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 1000
        })
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        let tempFilePaths = res.tempFilePaths;

        that.setData({
          tempFilePaths: tempFilePaths
        })
        /**
         * 上传完成后把文件上传到服务器
         */
        // console.log(tempFilePaths)
        var count = 0;
        var list = [] //待上传图片临时路径
        wx.showLoading()
        for (var i = 0, h = tempFilePaths.length; i < h; i++) {
          //上传文件
          wx.uploadFile({
            url: app.globalData.dataUrl + '/upload/uploadFile',
            filePath: tempFilePaths[i],
            name: 'file',
            header: {
              'content-type': 'multipart/form-data',
              'token': wx.getStorageSync('token')
            },
            success: function (ret) {
              var res = JSON.parse(ret.data)
              count++;
              //如果是最后一张,则隐藏等待中  
              if (count == tempFilePaths.length) {
                wx.hideLoading();
              }
              if (res.retCode == 'SUCCESS') {
                list.push(res.retData.url) //待上传图片临时路径
                that.setData({
                  tempFilePaths: list
                })
                console.log(that.data.tempFilePaths, '待上传的图片集合')
              } else {
                wx.showToast({
                  title: res.retMsg,
                  icon: "none",
                  duration: 1500
                })
              }
            },
            fail: function (res) {
              wx.hideLoading();
              wx.showModal({
                title: '错误提示',
                content: '上传图片失败',
                showCancel: false,
                success: function (res) {}
              })
            }
          });
        }
      }
    })
  },
  listenerButtonPreviewImage: function (e) { //预览图片方法
    let index = e.target.dataset.index;
    let that = this;
    console.log(that.data.tempFilePaths[index]);
    console.log(that.data.tempFilePaths);
    wx.previewImage({
      current: that.data.tempFilePaths[index],
      urls: that.data.tempFilePaths,
      //这根本就不走
      success: function (res) {
        //console.log(res);
      },
      //也根本不走
      fail: function () {
        //console.log('fail')
      }
    })
  },

  deleteImage: function (e) { //长按删除图片
    var that = this;
    var tempFilePaths = that.data.tempFilePaths;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          tempFilePaths.splice(index, 1);
        } else if (res.cancel) {
          return false;
        }
        that.setData({
          tempFilePaths: tempFilePaths
        });
        // console.log(that.data.tempFilePaths, '55')
      }
    })
  },

  // 选择word
  chooseWord(e){
    var that = this
    wx.chooseMessageFile({
      count: 1,
      type:'file',
      success(res){
        //截取文件后缀
        var fileType = res.tempFiles[0].name.replace(/.+\./,"");
        if(fileType!='doc' && fileType!='docx'&&fileType!='DOC'&&fileType!='DOCX' ){
          wx.showToast({
            title: '请选择word文档上传',
            icon:'none'
          })
          return
        }
        wx.showLoading({
          title: '上传中请稍等！',
          icon:'none',
          mask:true
        })
        //上传文件
        wx.uploadFile({
          url: app.globalData.dataUrl + '/upload/uploadFile',
          filePath: res.tempFiles[0].path,
          name: 'file',
          header: {
            'content-type': 'multipart/form-data',
            'token': wx.getStorageSync('token')
          },
          success: function (ret) {
            var ress = JSON.parse(ret.data)
            wx.hideLoading();
            if (ress.retCode == 'SUCCESS') {
              // console.log(ress.retData)
              let wordSrc = {name:res.tempFiles[0].name,path:ress.retData.url,size:res.tempFiles[0].size}
              that.setData({
                wordSrc:wordSrc
              })
            } else {
              wx.showToast({
                title: ress.retMsg,
                icon: "none",
                duration: 1500
              })
            }
          },
          fail: function (res) {
            wx.hideLoading();
            wx.showModal({
              title: '错误提示',
              content: '文件过大,上传失败',
              showCancel: false,
              success: function (res) {}
            })
          }
        });
      }
    })
  },
// 获取值
  getval(e) {
    let type = e.currentTarget.dataset.type

    if (type == 1) {
      this.setData({
        title: e.detail.value
      })
    } else if (type == 2) {
      this.setData({
        message: e.detail.value
      })
    } 
  },
  // 提交
  submit(){
    console.log(this.data.title)
    console.log(this.data.message)
    console.log(this.data.active)
    console.log(this.data.tempFilePaths[0])
    console.log(this.data.wordSrc.path)
    console.log(wx.getStorageSync('userId'))
    
    if(!this.data.title){
      wx.showToast({
        icon: 'none',
        title: '请输入标题！'
      });
      return
    }
    if(!this.data.message){
      wx.showToast({
        icon: 'none',
        title: '请输入内容！'
      });
      return
    }

    if(!this.data.tempFilePaths[0] && !this.data.wordSrc.path){
      wx.showToast({
        icon: 'none',
        title: '请选择上传文件！'
      });
      return
    }
    let param = {}
    if(this.data.active == 0){
      param = {
        xdtitle:this.data.title,
        content:this.data.message,
        userId:wx.getStorageSync('userId'),
        filetype:this.data.active,
        fileurl:this.data.tempFilePaths[0],
        filesize:'',
        filename:'',
      }
    }else if(this.data.active == 1){
      param = {
        xdtitle:this.data.title,
        content:this.data.message,
        userId:wx.getStorageSync('userId'),
        filetype:this.data.active,
        fileurl:this.data.wordSrc.path,
        filesize:this.data.wordSrc.size,
        filename:this.data.wordSrc.name,
      }
    }
    
    r.toPost('/experience/xdthApply', param, (res) => {
      wx.showToast({
        title: '发布成功！',
        icon:'none'
      })
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/understand/understand',
        })
      }, 1000);
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})